<template>
	<div class="edit-index-box">
		<div class="status-column">
			<m-column @typeChange="typeChange" @shopChange="shopChange"></m-column>
		</div>
		<div class="createNewStencil">
			<blue-btn text="新建模板"  :clickEvent="createNewStencil" style="padding-top:65px;text-align:right"></blue-btn>
		</div>
		<!-- 这是编辑的index页面 -->
		<div class="edit-index-content">
			<div class="left" v-if="false">
				<ul>
					<li v-for="(item, index) in liData" 
						:class="[li_active_index === item.index ? 'li_active' : '']"
						:key="index"
						@click="changeLiIndex(item.index)">
						{{item.name}}
					</li>
				</ul>
			</div>
			<div class="right">
				<table class="sv-table">
					<tr class="table-th">
						<th>模板名称</th>
						<th>更新时间</th>
						<th>状态</th>
						<th>操作</th>
					</tr>
					<tr v-for="(item, index) in templateList" :key="index" class="table-tr">
						<td>{{item.tpName | tpNameHandle}}({{item.rid}})</td>
						<td>{{getDate(item.updateTm)}}</td>
						<td>
							<span v-if="item.tpState===1">启用</span>
							<span v-if="item.tpState!=1">禁用</span>
						</td>
						<td style="text-align: center;" class="handle">
							<blue-btn text="装修模板" class="btn-group"  :clickEvent="editClickEvent.bind(this, item)"></blue-btn>
							<el-dropdown>
								<span class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</span>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item @click.native="enableClickEvent(item.rid, item.tpState,item.storeCode)" :class="item.tpState === 1 ? 'disabled' : ''">启用模板</el-dropdown-item>
									<el-dropdown-item @click.native="copyTemplateInfo(item)">复制模板</el-dropdown-item>
									<el-dropdown-item @click.native="modifyClickEvent(item)">重命名模板</el-dropdown-item>
									<el-dropdown-item @click.native="deleteTemplateData(item.rid, item.tpState,item.storeCode)" :class="item.tpState === 1 ? 'disabled' : ''">删除模板</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</td>
					</tr>
				</table>
				<div class="right-footer"></div>
			</div>
		</div>
		<edit-model ref="editModel" title="修改基本信息" :closeCallback="clearParams">
			<div class="modify-template-box slot-banner" slot="main">	
				<div>
					<p class="eidt-slot-title">
						<span class="required">*</span>模板名称
					</p>
					<input type="text" v-model="tpName"/>
				</div>
				<div>
					<p class="eidt-slot-title">
						<span class="required"></span>模板描述
					</p>
					<textarea v-model="tpDesc"></textarea>
				</div>
				<!-- <div>
					<p class="eidt-slot-title">
						<span class="required"></span>模板预览图
					</p>
					<m-upload :imgShowList="thumbnailImg" ref="upload"></m-upload>
				</div> -->
				<div class="fabu-box">
					<blue-btn text="确定" :clickEvent="modify"></blue-btn>
				</div>
			</div>
		</edit-model>
		<edit-model ref="mEditModel" title="新增模板">
			<div class="add-template-box slot-banner" slot="main">
				<div>
					<p class="eidt-slot-title">
						<span class="required">*</span>模板名称
					</p>
					<input type="text" v-model="tpName"/>
				</div>
				<div>
					<p class="eidt-slot-title">
						<span class="required"></span>模板描述
					</p>
					<textarea v-model="tpDesc"></textarea>
				</div>
				<div class="fabu-box">
					<blue-btn text="确定" :clickEvent="addClickEvent"></blue-btn>
				</div>
			</div>
		</edit-model>
		<edit-model ref="CopyEditModel" title="复制模板">
			<div class="add-template-box slot-banner" slot="main">
				<div>
					<p class="eidt-slot-title">
						<span class="required">*</span>复制到门店
					</p>
					<m-column-list @shopChangeCopy="shopChangeCopy"></m-column-list>
				</div>
				<div>
					<p class="eidt-slot-title">
						<span class="required">*</span>模板名称
					</p>
					<input type="text" v-model="tpNameCopy"/>
				</div>
				<div>
					<p class="eidt-slot-title">
						<span class="required"></span>模板描述
					</p>
					<textarea v-model="tpDescCopy"></textarea>
				</div>
				<div class="fabu-box">
					<blue-btn text="确定" :clickEvent="copyClickEvent"></blue-btn>
				</div>
			</div>
		</edit-model>
		<m-toast ref="mToast"></m-toast>
		<m-dialog ref="mDialog"></m-dialog>
	</div>
</template>

<script>
import "./index.css";
import BlueButton from "../../edit-components/BlueButton";
import Column from "./Column";
// import Column from "../../edit-components/AddPage/Column/index";
import ColumnList from "./Column/indexList"
import Dialog from "../../edit-components/Dialog";
import Toast from "../../edit-components/Toast";
import EditModel from "../../edit-components/EditModel";
import updated from "../../utils/TemplateAxios/add";
import enable from "../../utils/TemplateAxios/enable";
import deleteFn from "../../utils/TemplateAxios/delete";
import Card from "../../edit-components/Card";
import {mapMutations, mapGetters} from "vuex";
import ImgUpload from "../../real-components/ImgUpload2";
import {Dropdown,DropdownItem,DropdownMenu} from "element-ui";
import { enableOdisable } from '../../api/gw';
import deeCopy from "../../utils/deepCopy";
import axios from "axios";
import initLinkedList from "../../utils/settings/initLinkedList";
import {initEditComponentsList} from "../../helper/drag-plugin/initComponents";
export default {
	data() {
		return {
			liData: [
				{ name: "模板列表", index: 0 },
				{ name: "关于模板", index: 1 },
			],
			li_active_index: 0,
			tpName: "",
			tpDesc: "",
			thumbnailImg: [],
			updateItem: null,
			handleState:false,
			tpNameCopy:'',
			tpDescCopy:'',
			targetStoreCode: '',
			targetStoreName:'',
			copyOriginItem : {},
			isSameStore:false,
			specialArr:[]
		};
	},
	computed: {
		...mapGetters([
			"getConfigParams"
		]),
		//模板列表
		templateList() {
			return this.getConfigParams.templateConfigList.filter(item => {
				return item.tpDesc !== "specialtemplateforaddpages";
			}).sort((m, n) => {
				let time1 = m.updateTm || m.createTm;
				let time2 = n.updateTm || n.createTm; 
				return time2 - time1;
			});
		},
		specialDomTree() {
			let template = this.getConfigParams.templateConfigList.find(item => {
				return item.tpDesc === "specialtemplateforaddpages";
			});
			if (template) {
				let obj = JSON.parse(template.tpConfig);
				delete obj.config;
				return obj;
			} else {
				return {};
			}
		}
	},
	filters: {
		tpNameHandle(val){
			if(val){
				return val
			}else{
				return '--'
			}
		}
	},
	methods: {
		//门店改变，重新请求并渲染模板列表
		shopChange(item) {
			// console.log("父组件", item);
		},
		//版本改变，重新请求并渲染模板列表
		typeChange() {
			// console.log("父组件", item);
		},
		changeLiIndex(index) {
			this.li_active_index = index;
		},
		//编辑按钮的事件
		async editClickEvent(item) {
			// console.log("打印item",item)
			//读取本地的文件
			let testData = (await import("../../utils/settings/testData.js")).default;
			window.manifest = initLinkedList(JSON.parse(testData));
			// window.manifest = initLinkedList(JSON.parse(item.tpConfig) || {});
			//记录当前选则的模板参数
			this.setCurrentTemplate(item);
			this.$router.push({name: "home", query: {env: "edit"}});
			//让编辑组件为空
			initEditComponentsList({componentName: ""})
		},
		//删除按钮的事件
		deleteClickEvent(rid, tpState, storeCode) {
			if (tpState !=0){
				return
			}
			this.infoDialog("确定要删除该模板吗？", () => {
				let callback = (data) => {
					this.infoToast("模板删除成功");
					this.resetTemplateParams(data);
				}
				let errFn = (msg = "删除模板失败") => {
					this.infoToast(msg)
				}
				let params={}
				params.rid = rid
				params.storeCode = storeCode
				deleteFn(params, callback, errFn);
			});
		},
		deleteTemplateData(rid, tpState, storeCode){
			let main = this.$store.getters.getConfigParams.templateConfigList.find(item=>{
				return item.rid === rid
			}).tpConfig
			let linkListMain = initLinkedList(JSON.parse(main))
			//获取ID
			if(Object.keys(linkListMain).length===0){
				let url = api.goods_host + '/resourceConfig/resource/delete/' + storeCode;
				let params = {'relGroupList':[]}
				let options = {
					url: url,
					method: 'post',
					data:params,
					headers: {sessionId: getCookie("sessionId")}
				};
				axios(options).then((res) => {
					this.infoToast(res.data.msg)
				})
			return
			}
			let current = linkListMain.home.main.head
            let arr = []
            while (current) {
                let ComponentId = current.element.id
                arr.push(ComponentId)
                current = current.next
			}
			let url = api.goods_host + '/resourceConfig/resource/delete/' + storeCode;
			let params = {'relGroupList':arr}
			let options = {
				url: url,
                method: 'post',
                data:params,
                headers: {sessionId: getCookie("sessionId")}
			};
			axios(options).then((res) => {
            	if(res.status === 200 && res.data.returnCode === 1){
					//删除数据成功然后删除模板列表
					this.deleteClickEvent(rid, tpState, storeCode)
                }
			})


		},
		//启用按钮的事件
		enableClickEvent(rid, tpState, storeCode) {
			if (tpState !=0){
				return
			}
			this.infoDialog("确定要启用该模板吗？", () => {
				let callback = (data) => {
					this.resetTemplateParams(data);
				}
				let errFn = (msg = "启用模板失败") => {
					this.infoToast(msg)
				}
				let params = {}
				params.rid = rid
				params.storeCode = storeCode
				enable(params, callback, errFn);
			});
		},
		//修改基本信息的方法
		modifyClickEvent(item) {
			this.tpName = item.tpName;
			this.tpDesc = item.tpDesc;
			// this.thumbnailImg = item.tpThumbNail ? [item.tpThumbNail] : [];
			this.updateItem = item;
			this.$refs.editModel.showCover();
		},
		//调用更新的接口
		async modify() {
			if (!this.tpName) {
				this.infoToast("模板名称不能为空");
				return;
			}
			// let res = await this.$refs.upload.upload();
			this.$refs.editModel.hideCover();
			let params = {
				rid: this.updateItem.rid,
				tpName: this.tpName,
				tpDesc: this.tpDesc,
				tpConfig: this.updateItem.tpConfig,
				tpState: this.updateItem.tpState,
				storeCode: this.updateItem.storeCode
				// tpThumbNail: res.data.length ? res.data[0] : "",
			};
			let success = (data) => {
				this.resetTemplateParams(data);
				this.infoToast("信息修改成功");
			}
			let fail = (msg = "信息修改失败") => {
				this.infoToast(msg);
			}
			updated(params, success, fail);
			this.clearParams();
		},
		//显示提示框的方法
		infoDialog(msg, confirmFn) {
			this.$refs.mDialog.dialog({
				msg,
				confirmFn
			});
		},
		//显示Toast的方法
		infoToast(msg) {
			this.$refs.mToast.toast(msg);
		},
		clearParams() {
			// this.$refs.upload.deleteImg();
			// this.thumbnailImg = [];
		},
		...mapMutations([
			"setCurrentTemplate",
			"setDomTree",
			"setConfigParams"
		]),
		...mapMutations("gw", [
		]),
		/*如下是改版后新增的方法*/
		//将时间戳格式化返回
		getDate(time) {
			if (!time) {
				return "--";
			}
			let date = new Date(time);
			return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1)}-${date.getDate() > 9 ? date.getDate() : "0" + date.getDate()} ${date.getHours() > 9 ? date.getHours() : "0" + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes()}`;
		},
		createNewStencil(){
			this.$refs.mEditModel.showCover();
		},
		//如下是新增模板列表
		addClickEvent() {
			if (!this.tpName) {
				this.infoToast("模板名称不能为空");
				return;
			}
			this.$refs.mEditModel.hideCover();
			let params = {
				tpName: this.tpName,
				tpDesc: this.tpDesc,
				storeCode: localStorage.getItem("storeCode")
			};
			let success = (data) => {
				this.resetTemplateParams(data);
				this.infoToast("新增模板成功");
			}
			let fail = (msg = "新增模板失败") => {
				this.infoToast(msg);
			}
			updated(params, success, fail);
		},
		copyTemplateInfo(item){
			this.$refs.CopyEditModel.showCover();
			this.copyOriginItem = item
		},
		copyClickEvent() {
			this.confirmCopyAxios()
		},
		//获取当前模板下自定义页面的所有组件ID
		getSpecialPageCompentId(){
			let specialObj = this.$store.getters["gw/getSpecialTemplate"]
			let pageArray = this.$store.getters["gw/getSpecialTemplate"].config.pages
			let arr = []
			let Arry = []
			pageArray.forEach((item,index) => {
				if(item.type!=='buyGiftCard' && item.type!=='IntegralBuy' && item.pageIsShow){
					arr.push([item.path])
				}
			});
			for(let i=0; i<arr.length; i++){
				let _orginDom = specialObj[arr[i]];
                let headerList = _orginDom.header
				let mainList = _orginDom.main;
                let current = mainList.head;
                let finished = false;
                while (current) {
                    let ComponentId = current.element.id
                    Arry.push(ComponentId)
                    current = current.next;
                    if (!current && !finished) {
                        finished = true;
                        current = headerList.head;
                    }
                }
			}
			this.specialArr = Arry || []
		},
		//调用复制模板的接口
		confirmCopyAxios(){
				if(this.isSameStore) {
					this.$refs.CopyEditModel.hideCover();
					this.$refs.mToast.toast('复制失败，模板无法复制到本门店');
					return
					}
                //选择的目标门店信息
				let storeCode = localStorage.getItem("storeCode")
				let main = this.$store.getters.getConfigParams.templateConfigList.find(item=>{
					return item.rid ===this.copyOriginItem.rid
				}).tpConfig
				let linkListMain = initLinkedList(JSON.parse(main))
				if( Object.keys(linkListMain).length===0){
					this.infoToast("模板内容为空，复制模板失败");
					return
				}
				//获取ID
				let current = linkListMain.home.main.head
                let arr = []
                while (current) {
                    let ComponentId = current.element.id
                    arr.push(ComponentId)
                    current = current.next
				}
                //调用复制页面的接口
                let url = api.goods_host + '/resourceConfig/resource/replications/' + storeCode + '/'+ this.targetStoreCode;
				let params = {'relGroupList':arr}
				let options = {
					url: url,
                    method: 'post',
                    data:params,
                    headers: {sessionId: getCookie("sessionId")}
				};
				axios(options).then((res) => {
                    if(res.status === 200 && res.data.returnCode === 1){
						//调用新增模板（复制的时候需要新增一条数据）
						this.shopCopyAddTemplate()
						this.$refs.CopyEditModel.hideCover();
						this.infoToast("复制模板成功");
						this.tpNameCopy = ''
						this.tpDescCopy = ''
                    }else{
						this.$refs.CopyEditModel.hideCover();
						this.infoToast("复制模板失败");
						this.tpNameCopy = ''
						this.tpDescCopy = ''
					}
				})
		},
		shopCopyAddTemplate(){
			if (!this.tpNameCopy) {
				this.infoToast("模板名称不能为空");
				return;
			}
			let params = {
				tpName: this.tpNameCopy,
				tpDesc: this.tpDescCopy,
				storeCode: this.targetStoreCode,//目标门店的storeCode
				tpConfig: deeCopy(this.copyOriginItem).tpConfig
			};
			let success = (data) => {
				console.log("打印tpConfig",data[0].tpConfig)
				this.resetTemplateParams(data);
				// this.infoToast("新建模板成功");
			}
			let fail = (msg = "复制模板失败") => {
				// this.infoToast(msg);
			}
			updated(params, success, fail);
		},
		shopChangeCopy(item) {
			console.log("aa",item)
			//获取目标门店的storeCode
			this.targetStoreCode = item.storeCode
			this.targetStoreName = item.name
			if(this.targetStoreName === localStorage.getItem('storeName')){
				this.$refs.mToast.toast('模板无法复制到本门店，请选择其他门店');
				this.isSameStore = true
			}
			this.$store.commit("lxn/setstoreCodeIndex", item.eqIndex)
		}
	},
	components: {
		"blue-btn": BlueButton,
		"m-dialog": Dialog,
		"m-toast": Toast,
		"m-card": Card,
		"edit-model": EditModel,
		"m-upload": ImgUpload,
		"m-column": Column,
		"el-dropdown":Dropdown,
		"el-dropdown-item":DropdownItem,
		"el-dropdown-menu":DropdownMenu,
		"m-column-list":ColumnList
	},
	created() {
	},
	mounted(){
	}
};
</script>
<style scoped>
	.status-column {
		width: 100%;
		height: 50px;
		margin-top: 30px;
		/* display: flex;
		justify-content: flex-end; */
	}
	/* 如下是改版后的新增加样式 */
	.btn-group{
		display:inline-block
	}
	.sv-table{
		width:70%;
		margin:0 auto
	}
	.table-th{
		height:50px;
	}
	.table-tr{
		height:50px;
	}
	.createNewStencil{
		/* float:right; */
		/* margin-right: 242px; */
		width:85%;
		margin-top:50px;
	}
	.bg-box-active{
		 height: 200px
	}
	/* 操作按钮的样式 */
	.handle-box {
		position: relative;
	}
	.bg-box {
		cursor: pointer;
		position: absolute;
		left: 0; 
		top: 0px; 
		overflow: hidden;
		padding: 15px;
		padding-top: 0;
		box-sizing: content-box;
		width: 100%;
		margin-left: -15px;
		height: 0;
		transition: all 0.3s;
		z-index: 10;
	}
	.button-box {
		border: 1px solid #e6ebf5;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0 ,0, .1);
		padding: 8px 0;
		background: #fff;
}
.bg-box-move {
	margin-top: 15px; 
}
.button-box input {
	border: 0;
	height: 36px;
	outline: none;
	line-height: 36px;
	background: #fff; 
	color: #444;
	width: 100%;
	cursor: pointer;
	transition: all 0.2s;
}
 .button-box input:hover {
	background-color: #ecf5ff;
    color: #66b1ff;
} 
.el-dropdown-link{
	width: 100px;
    height: 28px;
    border: 1px solid #eee;
    display: inline-block;
    background-color: #3876ae;
    line-height: 28px;
    color: #fff;
    border-radius: 3px;
}
 .disabled {
	cursor: not-allowed;
	background: #ddd;
	border-radius: 0;
	opacity: 0.2;
} 
 .disabled:hover {
	background: #ddd;
	color: #444;
	opacity: 0.2;
}
.handle .el-dropdown {
	border:none;
}
</style>


